package com.logistics.controller;

import com.logistics.common.Result;
import com.logistics.entity.User;
import com.logistics.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/api/user")
public class UserController {
    
    @Autowired
    private UserService userService;
    
    @PostMapping("/register")
    public Result register(@RequestBody User user) {
        return userService.register(user);
    }
    
    @PostMapping("/login")
    public Result login(@RequestBody User user, HttpSession session) {
        Result result = userService.login(user.getUsername(), user.getPassword());
        if (result.getCode() == 200) {
            // 登录成功，将用户信息存储到session中
            session.setAttribute("user", result.getData());
            // 设置session过期时间为30分钟
            session.setMaxInactiveInterval(30 * 60);
        }
        return result;
    }
    
    @GetMapping("/info")
    public Result getUserInfo(HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return Result.error(401, "未登录");
        }
        return Result.success(user);
    }
    
    @GetMapping("/{id}")
    public Result getUser(@PathVariable Long id) {
        return userService.getUser(id);
    }
    
    @GetMapping("/list")
    public Result listUsers() {
        return userService.listUsers();
    }
    
    @PutMapping
    public Result updateUser(@RequestBody User user) {
        return userService.updateUser(user);
    }
    
    @DeleteMapping("/{id}")
    public Result deleteUser(@PathVariable Long id) {
        return userService.deleteUser(id);
    }
    
    @GetMapping("/logout")
    public Result logout(HttpSession session) {
        session.removeAttribute("user");
        return Result.success();
    }
} 